package com.gitee.cirnochat.notification.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.cirnochat.common.utils.RedissonLockUtil;
import com.gitee.cirnochat.notification.mapper.JiguangPushTokenMapper;
import com.gitee.cirnochat.notification.model.entity.JiguangPushToken;
import com.gitee.cirnochat.notification.service.JiguangPushTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static com.gitee.cirnochat.common.constant.RedisKey.JIGUANG_PUSH_TOKEN_LOCK_KEY;

/**
* @author FlanChan
* @description 针对表【jiguang_push_token(极光推送令牌表)】的数据库操作Service实现
* @createDate 2025-06-19 17:09:11
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class JiguangPushTokenServiceImpl extends ServiceImpl<JiguangPushTokenMapper, JiguangPushToken>
    implements JiguangPushTokenService {
    private final RedissonLockUtil redissonLockUtil;

    @Override
    public void setJPushToken(String registerId, String deviceId, Long userId) {
        // 根据deviceId和userId进行token查询
        JiguangPushToken token = this.getJPushTokenByDeviceIdAndUserId(deviceId, userId);
        if (token == null) {
            redissonLockUtil.redissonDistributedLocks(JIGUANG_PUSH_TOKEN_LOCK_KEY + deviceId, () -> {
                JiguangPushToken againToken = this.getOne(new LambdaQueryWrapper<>(JiguangPushToken.class)
                        .eq(JiguangPushToken::getDeviceId, deviceId)
                        .eq(JiguangPushToken::getUserId, userId));
                if (againToken == null) {
                    JiguangPushToken jiguangPushToken = new JiguangPushToken();
                    jiguangPushToken.setUserId(userId);
                    jiguangPushToken.setDeviceId(deviceId);
                    jiguangPushToken.setRegisterId(registerId);
                    this.save(jiguangPushToken);
                }
            });
        }
    }

    @Override
    public Boolean checkJPushToken(String deviceId, Long userId) {
        return this.exists(new LambdaQueryWrapper<>(JiguangPushToken.class)
                .eq(JiguangPushToken::getDeviceId, deviceId)
                .eq(JiguangPushToken::getUserId, userId));
    }


    @Override
    public JiguangPushToken getJPushTokenByDeviceIdAndUserId(String deviceId, Long userId) {
        return this.getOne(new LambdaQueryWrapper<>(JiguangPushToken.class)
                .eq(JiguangPushToken::getDeviceId, deviceId)
                .eq(JiguangPushToken::getUserId, userId));
    }
}




